import 'package:flutter/material.dart';

///数据加载完成之前，界面先显示骨架屏
mixin LoadingDataSkeleton<T> {

  Widget loadingData(BuildContext context, AsyncSnapshot<T> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return noneWidget(context);
      case ConnectionState.waiting:
        return waitingWidget(context);
      case ConnectionState.active:
        return activeWidget(context);
      case ConnectionState.done:
        return doneWidget(context, snapshot.data);
    }
  }

  Widget noneWidget(BuildContext context) => const LoadingSkeleton();
  Widget waitingWidget(BuildContext context) => noneWidget(context);
  Widget activeWidget(BuildContext context) => noneWidget(context);
  Widget doneWidget(BuildContext context, T? data);
}

///加载时的占位骨架
class LoadingSkeleton extends StatelessWidget {

  const LoadingSkeleton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> list = List.generate(5, (index) {
      return Container(
          margin: const EdgeInsets.only(bottom: 10),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colors.white,
          ),
          child: Column(
            children: [
              _SkeletonItem(),
              Container(height: 10),
              _SkeletonItem(),
            ],
          ));
    });
    return Padding(
        padding: const EdgeInsets.all(20), child: ListView(children: list));
  }
}

class _SkeletonItem extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SkeletonItemState();
}

class _SkeletonItemState extends State<_SkeletonItem> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  late Animation gradientPosition;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        duration: const Duration(milliseconds: 1500), vsync: this);

    gradientPosition = Tween<double>(
      begin: -3,
      end: 20,
    ).animate(
      CurvedAnimation(parent: _controller, curve: Curves.linear),
    )..addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
    _controller.repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 20,
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment(gradientPosition.value, 0),
              end: const Alignment(-1, 0),
              colors: const [
                Color(0xFFF2F3F5),
                Color(0xFFE6E6E6),
                Color(0xFFF2F3F5)
              ])),
    );
  }
}